<?php

########################################################################################
#
# 版权所有
# 通用翻页类，
# 使用方法
# $page = new Page();
# 结果集
# $res  = $page->get_page_arr($sql);
# 分页链接
# $page_link = $page->get_page_link();
# 默认关闭自定义样式
# $style_flag  = 1; 开启自定义样式
# eg :
# .page_link { font-size:12px; }
#
########################################################################################
class page {
	public $num_everypage;   #	每一页显示的行数
	public $pagename;   #	为显示的各条信息链向的处理页面
	public $view_flag = 0; #	0 eg 当前页在第一页时上一页不显示
	public $style_num = 3; # 	分页格式
	public $style_flag = 1; #	自定义样式开关 0关闭自定义样式 1 开启自定义样式
	public $page_link_sign;
	public $page_link_space;
	public $show_dialog = true;
	public $pageBetween;   #	多少页分段
	public $useReWrite;   #	多少页分段
	public $sum_row;    #	所查数据库的所有行数
	private $sum_page;    #	总共有多少页，有class内部计算得出
	private $db;     # 	和外部的phplib的类连接变量 $GLOBALS['context']->db
	private $now_page;   # 	当前页数
	public $ajax_page = 1;  # 	0 为非ajax分页
	public $ajax_url;
	public $ajax_div;
	public $mc;

	private function getCache() {
		$this->mc = $GLOBALS['context']->cache;
	}

	private function getCacheRes($sql) {
		$key = md5($sql);
		if (!($res = $this->mc->get($key))) {
			$res = $this->db->getAll($sql);
			$this->mc->set($key, $res);
		}
		return $res;
	}

	public function __construct() {
		$this->getCache();
		//		if ($this->num_everypage == '') {
		//			$this->num_everypage = PAGE_SIZE;	# 每页显示的条数
		//		}
		if ($this->pagename == '') {
			$tmp_name = $_SERVER['PHP_SELF'];
			$this->pagename = basename($tmp_name) . '?';
		}
		if ($this->page_link_sign == '') {
			$this->page_link_sign = "";
		}
		if ($this->page_link_space == '') {
			//$this->page_link_space = "&nbsp;";
			$this->page_link_space = "";
		}
		/*
		 if ($this->pageBetween == '') {
		 $this->pageBetween = isset($request['pageBetween'])?$request['pageBetween']:10;
		 }
		 */
		if (!empty($_GET['page'])) {
			$this->now_page = $_GET['page'];
		}
		if (!empty($_GET['ajax_page'])) {
			$this->ajax_page = $_GET['ajax_page'];
		} else {
			$this->ajax_page = 'page_ajax';
		}

		$this->num_everypage = PAGE_SIZE;
		if (!$this->db)
		$this->db = $GLOBALS['context']->db;
	}

	/**
	 * 或获取数据库的信息，通过一个sql语句
	 */
	public function get_page_arr($sql, array & $request, $count_sql=1) {
		$this->num_everypage = isset($request['num_per_page']) ? $request['num_per_page'] : PAGE_SIZE;
		$this->pageBetween = isset($request['pageBetween']) ? $request['pageBetween'] : 10;
		$this->now_page = (isset($request['page']) && $request['page']) ? $request['page'] : 1;
		$this->show_dialog = isset($request['show_dialog']) ? $request['show_dialog'] : $this->show_dialog;
		//定义变量ajax_url ,ajax_div;
		$this->ajax_url = isset($request['ajax_url']) ? $request['ajax_url'] : null;
		$this->ajax_div = isset($request['ajax_div']) ? $request['ajax_div'] : null;
		if (!empty($sql)) {
			/*
			if ($count_sql) {
				$new_arr = explode('from', strtolower($sql));
				$distinct = explode('distinct', strtolower($sql));
				if (isset($distinct[1])) {
					$count_str_arr = explode(',', $distinct[1]);
					$count_str = 'DISTINCT ' . $count_str_arr[0];
				} else {
					$count_str = ' * ';
				}
				$count_sql = 'select count(' . $count_str . ') as num from ' . $new_arr[1];
			} else {
				$count_sql = 'SELECT COUNT(*) AS num FROM (' . $sql . ') TEMP';
			}
			*/
			$pattern = array("\s", "\r\n", "\n", "\r", "\t", "\v");
			$count_sql = str_replace($pattern,' ',$sql);
			$pos = stripos($count_sql, ' from ');
			$is_group = stripos($count_sql, ' group by ');
			$is_count = stripos($count_sql, 'count(');
			$is_sum = stripos($count_sql, 'sum(');
			if ($pos !== false && $is_count === false && $is_sum === false) {
				$pos2 = stripos($count_sql, ' distinct ');
				if ($pos2 === false) {
					$count_sql = 'SELECT COUNT(*) AS num' . substr($count_sql, $pos);
				} else {
					$sub_sql = substr($count_sql, $pos2, $pos-$pos2);
					$pos3 = stripos($sub_sql, ',');
					if ($pos3 === false) {
						$count_sql = 'SELECT COUNT('. substr($count_sql, $pos2, $pos2-$pos) .') AS num' . substr($count_sql, $pos);
					} else {
						$pos3 = stripos($sql, ',');
						$count_sql = 'SELECT COUNT('. substr($count_sql, $pos2, $pos3-$pos2) .') AS num' . substr($count_sql, $pos);
					}
				}
			} else {
				$count_sql = 'SELECT COUNT(*) AS num FROM (' . $sql . ') TEMP';
			}
			$row = $this->db->get_row($count_sql);
			$num = isset($row['num'])?$row['num']:0;
			if ($num) {
				$count = 0;
				//$this->sum_row = $this->num_rows(); 	#	总记录数
				$this->sum_row = $num;  #	总记录数
				#	sum_page 总页数
				if ($this->sum_row <= $this->num_everypage) {
					$this->sum_page = 1;
				} elseif (($this->sum_row) > ($this->num_everypage)) {
					if (($this->sum_row) % ($this->num_everypage) == 0) {
						$this->sum_page = ($this->sum_row) / ($this->num_everypage);
					} else {
						$this->sum_page = ceil($this->sum_row / $this->num_everypage);
					}
				}
				#	end

				$start_row = ($this->now_page - 1) * $this->num_everypage; #	开始的行号为：
				$end_row = ($this->now_page) * $this->num_everypage;  #	结束的行号为：
				#	 得到数组
				$sql = $sql . " limit " . $start_row . "," . $this->num_everypage;
				//$res = $this->getCacheRes($sql);

				$res = $this->db->getAll($sql);
				return $res;
			} else {
				//throw new Error("数据库出错！",3000);
			}
		} else {
			//echo "ddd";
			//die;
			//throw new Error("你还没有输入SQL语句！",3000);
		}
	}

	/**
	 * 返回总页数
	 */
	public function sum_page() {
		return "" . $this->sum_page . "页" . $this->page_link_space;
	}

	/**
	 * 总记录数
	 */
	public function sum_row() {
		return "" . $this->sum_row . "条" . $this->page_link_space;
	}

	/**
	 * 首页
	 */
	public function first_page() {
		$str = '';
		if ($this->now_page > 1) {
			#	是否 ajax 分
			if ($this->ajax_page) {
				$str = "<a href='javascript:{$this->ajax_page}(1,\"{$this->ajax_url}\",\"{$this->ajax_div}\");'>首页</a>";
			} else {
				$str = "<a href='" . $this->pagename . "&page=1'>首页</a>";
			}
			$str .= $this->page_link_space;
		} else {
			if ($this->view_flag) {
				$str = "首页";
			} else {
				$str = "<img src='" . get_theme_url('images/btn_pre_out_01.gif') . "' alt='上一页' width='20' height='20'>";
			}
			$str .= $this->page_link_space;
		}
		return $str;
	}

	/**
	 * 上一个区间
	 */
	public function last_zone() {
		$str = "";
		if ($this->now_page > $this->pageBetween) {
			$tmp_page = $this->now_page - $this->pageBetween;
			# 	是否 ajax 分
			if ($this->ajax_page) {
				$str = "<a href='javascript:{$this->ajax_page}($tmp_page,\"{$this->ajax_url}\",\"{$this->ajax_div}\");'>上{$this->pageBetween}页</a>";
			} else {
				$str = "<a href='{$this->pagename}&page=$tmp_page'>上{$this->pageBetween}页</a>";
			}
			$str .= $this->page_link_space;
		} else {
			if ($this->view_flag) {
				$str = "上{$this->pageBetween}页";
				$str .= $this->page_link_space;
			}
		}
		return $str;
	}

	/**
	 * 下一个区间
	 */
	public function next_zone() {
		$str = "";
		if ($this->now_page + $this->pageBetween < $this->sum_page) {
			$tmp_page = $this->now_page + $this->pageBetween + 1;
			# 	是否 ajax 分
			if ($this->ajax_page) {
				$str = "<a href='javascript:{$this->ajax_page}($tmp_page);'>下{$this->pageBetween}页</a>";
			} else {
				$str = "<a href='{$this->pagename}&page={$tmp_page}'>下{$this->pageBetween}页</a>";
			}
			$str .= $this->page_link_space;
		} else {
			if ($this->view_flag) {
				$str = "下{$this->pageBetween}页";
				$str .= $this->page_link_space;
			}
		}
		return $str;
	}

	/**
	 * 上一页
	 */
	public function last_page() {
		$str = "";
		if ($this->now_page > 1) {
			$tmp_page = $this->now_page - 1;
			# 	是否 ajax 分
			if ($this->ajax_page) {
				if ($this->show_dialog)
				$str = "<a class='os_page_btn_pre_curr'  href='javascript:{$this->ajax_page}($tmp_page);'></a>";
				else
				$str = "<a class='os_page_btn_pre'  href='javascript:{$this->ajax_page}($tmp_page,\"{$this->ajax_url}\",\"{$this->ajax_div}\");'></a>";
			}else {
				$str = "<a href='{$this->pagename}&page=$tmp_page'>上页</a>";
			}
			$str .= $this->page_link_space;
		} else {
			if ($this->view_flag) {
				$str = "上页";
				$str .= $this->page_link_space;
			}
		}
		return $str;
	}

	/**
	 * 下一页
	 */
	public function next_page() {
		$str = "";
		if ($this->now_page < $this->sum_page) {
			$tmp_page = $this->now_page + 1;
			# 	是否 ajax 分
			if ($this->ajax_page) {
				if ($this->show_dialog)
				$str = "<a class='os_page_btn_next_curr' href='javascript:{$this->ajax_page}($tmp_page);'></a>";
				else
				$str = "<a class='os_page_btn_next_curr' href='javascript:{$this->ajax_page}($tmp_page ,\"{$this->ajax_url}\",\"{$this->ajax_div}\");'></a>";
			}else {
				$str = "<a href='{$this->pagename}&page=$tmp_page'>下页</a>";
			}
			$str .= $this->page_link_space;
		} else {
			if ($this->view_flag) {
				$str = "下页";
				$str .= $this->page_link_space;
			}
		}
		return $str;
	}

	/**
	 * 尾页
	 */
	public function lastone_page() {
		$str = "";
		if ($this->now_page < $this->sum_page) {
			# 	是否 ajax 分
			if ($this->ajax_page) {
				$str = "<a href='javascript:{$this->ajax_page}($this->sum_page,\"{$this->ajax_url}\",\"{$this->ajax_div}\");'>尾页</a>";
			} else {
				$str = "<a href='{$this->pagename}&page={$this->sum_page}'>尾页</a>";
			}
			$str .= $this->page_link_space;
		} else {
			if ($this->view_flag) {
				$str = "尾页";
				$str .= $this->page_link_space;
			}
		}
		return $str;
	}

	/**
	 * 数字页字符串
	 */
	public function get_num() {
		$str = "";
		# 起始数字
		$half = floor($this->pageBetween / 2);
		if ($this->now_page - $half > 1) {
			$start_num = $this->now_page - $half;
		} else {
			$start_num = 1;
		}

		# 结束数字
		if ($start_num > 1) {
			$half = ceil($this->pageBetween / 2);
			if ($this->now_page + $half < $this->sum_page) {
				$end_num = $this->now_page + $half;
			} else {
				$end_num = $this->sum_page;
			}
		} else {
			$end_num = $this->pageBetween;
			if ($end_num > $this->sum_page) {
				$end_num = $this->sum_page;
			}
		}
		# 特殊情况
		if ($end_num == $this->sum_page) {
			if ($end_num - $start_num < $this->pageBetween) {
				if (1 != $start_num) {
					while ($start_num > 1) {
						$start_num--;
						if ($end_num - $start_num >= $this->pageBetween) {
							break;
						}
					}
				}
			}

			if ($end_num - $start_num + 1 > $this->pageBetween) {
				$start_num = $end_num - $this->pageBetween + 1;
			}
		} else {
			if ($end_num - $start_num + 1 > $this->pageBetween) {
				$end_num = $start_num + $this->pageBetween - 1;
			}
		}
		for ($i = $start_num; $i <= $end_num; $i++) {
			if ($i == $this->now_page) {
				if ($i == 1) {
					$str .="<span>第</span><a class='os_page_btn_pre' href ='javascript:void(0)'></a><a href ='javascript:void(0)' class='os_page_btn_curr'>$i</a>";
				} elseif ($i == $this->sum_page) {
					$str .="<a href ='javascript:void(0)' class='os_page_btn_curr'>$i</a><a class='os_page_btn_next' href ='javascript:void(0)'></a><span>页</span>";
				} else {
					$str .= "<a href ='javascript:void(0)' class='os_page_btn_curr'>$i</a>";
				}
			} else {
				#	是否 ajax 分
				if ($this->ajax_page) {
					if ($this->show_dialog)
					$str .= "<a href='javascript:{$this->ajax_page}($i);' >$i</a>";
					else
					$str .= "<a href='javascript:{$this->ajax_page}($i ,\"{$this->ajax_url}\",\"{$this->ajax_div}\");' >$i</a>";
				}else {
					$str .= "<a href='{$this->pagename}&page=$i' >$i</a>";
				}
			}
			$str .= $this->page_link_space;
		}

		return $str;
	}

	/**
	 * 输出下面的行连接显示
	 */
	public function get_page_link($errormsg = "对不起，还没有记录！") {
		if ($this->sum_row == 0) {
			return $errormsg;
		}
		$cname = "get_link_style" . $this->style_num;
		$content = $this->$cname();
		$content = "" . $content;
		if (empty($this->style_flag)) {
			//$content .= "<style type='text/css'>.page_link { font-size:13px; }.page_link a { text-decoration:none;}</style>";
		}
		#	ajax 分页转换编码
		/*
		 if($this->ajax_page){
		 //$content = auto_charset($content,"GBK","UTF-8");
		 $content = iconv("GBK","UTF-8", $content);
		 }
		 */
		$url = get_theme_url('images/btn_sure_01.gif');
		if ($this->show_dialog) {
			$id = str_replace('.', '_', $this->ajax_page).'_'.$this->sum_page;
			$content .= "</li><li><span>共" . $this->sum_page . "页 到第</span></li>
                            <li><input class='os_page_count' maxlength=3 type='text' value='{$this->now_page}' id='{$id}gotopage' size='3' maxlength='4' /></li>
                            <li><span>页</span></li>
                            <li><a class='os_page_btn_sure' href='javascript:modCheckPages.check({$this->sum_page},\"{$this->ajax_page}\");' ></a></li>"; //\"gotopage\",
		}else {
			$content .= "</li><li><span>共" . $this->sum_page . "页 到第</span></li>
                            <li><input class='os_page_count' maxlength=3 type='text' value='{$this->now_page}' id='gotopageajax' size='3' maxlength='4' /></li>
                            <li><span>页</span></li>
                            <li><a class='os_page_btn_sure' href='javascript:redirectPage(\"gotopageajax\",\"{$this->ajax_url}\",\"{$this->ajax_div}\",{$this->sum_page},{$this->now_page});' ></a></li>";
		}

		/*
		 $content .="<span class='pag_font'>共<b id='page_count'>".$this->sum_page."</b> 页 到第</span>
		 <span><input type='text' id='gotopage' class='pag_textbox' size='3' maxlength='4' value=''></span>
		 <span class='pag_font_02'>页</span><span><a href='javascript:redirectPage(\"gotopage\",\"{$this->ajax_url}\",\"{$this->ajax_div}\",{$this->sum_page},{$this->now_page});'
		 <img src='".$url."' alt='确定' width='38' height='20'></a></span></span>
		 ";
		 */
		return $content;
	}

	public function get_info($errormsg = "") {
		$info = '';
		$info .="每页显示{$this->num_everypage}条  共{$this->sum_row}条";
		return $info;
	}

	/**
	 *
	 * 100页 5000条 首页 上10页 上页 11 12 13 14 15 16 17 18 19 20 下页 下10页 尾页
	 *
	 */
	public function get_link_style1() {
		$content = "";
		$content .= $this->sum_page();
		$content .= $this->sum_row();
		$content .= $this->first_page();
		$content .= $this->last_zone();
		$content .= $this->last_page();
		# 数字
		$content .= $this->get_num();
		# end
		$content .= $this->next_page();
		$content .= $this->next_zone();
		$content .= $this->lastone_page();
		return $content;
	}
    public function get_page_link_no_ajax($errormsg = "") {
        if ($this->sum_row == 0){
            if(!empty($this->errormsg)) return $this->errormsg;
            else return $errormsg;
        }
        $cname = "get_link_style".$this->style_num;
        $content = $this->$cname();
        if($this->style_num <=4) {
            $id = str_replace('.', '_', $this->ajax_page).'_'.$this->sum_page;
            $content .= "</li><li><span>共" . $this->sum_page . "页 到第</span></li>
                            <li><input class='os_page_count' maxlength=3 type='text' value='{$this->now_page}' id='{$id}gotopage' size='3' maxlength='4' /></li>
                            <li><span>页</span></li>
                            <li><a class='os_page_btn_sure' href='javascript:modCheckPages.check({$this->sum_page},\"{$this->ajax_page}\");' ></a></li>"; //\"gotopage\",
        } else {

        }
        return $content;
    }

	/**
	 *
	 *  首页 上10页 上页 11 12 13 14 15 16 17 18 19 20 下页 下10页 尾页
	 *
	 */
	public function get_link_style2() {
		$content = "";
		$content .= $this->first_page();
		$content .= $this->last_zone();
		$content .= $this->last_page();
		# 数字
		$content .= $this->get_num();
		# end
		$content .= $this->next_page();
		$content .= $this->next_zone();
		$content .= $this->lastone_page();
		return $content;
	}

	/**
	 *
	 *   上页 11 12 13 14 15 16 17 18 19 20 下
	 *
	 */
	public function get_link_style3() {
		$content = "";
		$content .= $this->last_page();
		# 数字
		$content .= $this->get_num();
		# end
		$content .= $this->next_page();



		return $content;
	}

	/**
	 *
	 *   11 12 13 14 15 16 17 18 19 20
	 *
	 */
	public function get_link_style4() {
		$content = "";
		# 数字
		$content .= $this->get_num();
		# end
		return $content;
	}

	/**
	 *
	 *   上页 / 下
	 *
	 */
	public function get_link_style5() {
		$content = "";
		$content .= $this->last_page();
		$content .= " / ";
		$content .= $this->next_page();
		return $content;
	}
	public function get_page_arr_no_ajax(array & $request){
		$this->num_everypage = isset($request['num_per_page'])?$request['num_per_page']:PAGE_SIZE;
		$this->pageBetween = isset($request['pageBetween'])?$request['pageBetween']:10;
		$this->now_page = isset($request['page']) ?$request['page']:1;
		//定义变量ajax_url ,ajax_div;
		$this->ajax_url = isset($request['ajax_url']) ?$request['ajax_url']:null;
		$this->ajax_div = isset($request['ajax_div']) ?$request['ajax_div']:null;
		$this->sum_row = isset($request['sum_row']) ?$request['sum_row']:0;
		$this->show_dialog = isset($request['show_dialog']) ?$request['show_dialog']:true;
		//$this->pagename = isset($request['page_name']) ?$request['page_name']:null;
		//$this->ajax_page = isset($request['ajax_page']) ?$request['ajax_page']:1;
		if(empty($this->now_page)){
			$this->now_page = 1;
		}
		if ($this->sum_row){
			$count = 0;
			if ($this->sum_row <= $this->num_everypage) {
				$this->sum_page = 1;
			}elseif (($this->sum_row) > ($this->num_everypage)) {
				if (($this->sum_row) % ($this->num_everypage) == 0) {
					$this->sum_page = ($this->sum_row) / ($this->num_everypage);
				} else {
					$this->sum_page = ceil($this->sum_row / $this->num_everypage);
				}
			}
			$start_row = ($this->now_page - 1) * $this->num_everypage;	#	开始的行号为：
			$end_row = ($this->now_page) * $this->num_everypage;		#	结束的行号为：
		}
	}
	//获得分页的结果集 同时获得分页条
	public function get_page_row($obj, array & $request, array & $response){
		$request['num_per_page'] = isset($request['num_per_page']) ? $request['num_per_page'] : PAGE_SIZE;
		$request['page'] = isset($request['page']) && $request['page'] ? $request['page'] : 1;
		$request['msg'] = isset($request['msg']) ? $request['msg'] : '';
		$this->sum_row = $obj->row_count_by();
		/*排序开始*/
		$orderBy = isset($request['orderby']) ? $request['orderby']: 'desc';
		if ( isset ( $request['order'] ) && ! empty ( $request['order'] ) ) {
			if (strtolower($orderBy)=='desc') {
				$obj->order($request['order']);
			} else {
				$obj->order($request['order'], false);
			}
		}
		/*排序结束*/
		$request['sum_row'] = $this->sum_row;
		if (!isset($request['export']) || !$request['export']) {
				$obj->limit($request['num_per_page'], $request['num_per_page']*($request['page']-1));
		}
		$response['get_page_row'] = $obj->set_memcache(true)->find_all_by();
		$this->get_page_arr_no_ajax($request);
		$response['page_link'] = $this->get_page_link();
		$response['page_info'] = $this->get_info ();
		$response['data'] = array(
			'code' => 0,
			'data' => array(
					'page_items'=>$response['get_page_row'],
					'page_link'=>$response['page_link'],
					'page_info'=>$response['page_info']
				)
		);
	}
	public function list_pages($obj, array & $request){
		$request['num_per_page'] = (isset($request['page_size']) && $request['page_size']) ? $request['page_size'] : 30;
		$request['page'] = (isset($request['page']) && $request['page']) ? $request['page'] : 1;
		$this->sum_row = $obj->row_count_by();
		/*排序开始*/
		$orderBy = isset($request['orderby']) ? $request['orderby']: 'desc';
		if ( isset ( $request['order'] ) && ! empty ( $request['order'] ) ) {
			if (strtolower($orderBy)=='desc') {
				$obj->order($request['order']);
			} else {
				$obj->order($request['order'], false);
			}
		}
		/*排序结束*/
		$request['sum_row'] = $this->sum_row;
		$obj->limit($request['num_per_page'], $request['num_per_page']*($request['page']-1));
		$get_page_row = $obj->set_memcache(true)->find_all_by();
		$this->get_page_arr_no_ajax($request);
		$data = array(
            'page_items'=>$get_page_row,
            'page_info'=>array(
                'current_page' => $this->now_page,
                'pages' => $this->sum_page,
                'page_size' => $this->num_everypage,
                'total' => $this->sum_row
            )
		);
		return $data;
	}
}
